package br.com.pyramides.facade;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import br.com.pyramides.dao.iface.IGenericDAO;
import br.com.pyramides.facade.iface.IGenericFacade;
import org.hibernate.criterion.Criterion;

/**
 * 
 * @author Lessandro
 */
public abstract class GenericFacade<T, ID extends Serializable> implements IGenericFacade<T, ID>, Serializable {

    protected IGenericDAO<T, ID> genericDAO;

    @Override
    public void setGenericDAO(IGenericDAO<T, ID> genericDAO) {
        this.genericDAO = genericDAO;
    }

    public GenericFacade() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    private Class<T> persistentClass;

    public Class<T> getPersistentClass() {
        return this.persistentClass;
    }

    @Override
    public void exclui(T entity) {
        try {
            genericDAO.exclui(entity);
        } catch (Exception ex) {
        }
    }

    @Override
    public T buscaPeloID(ID id) {
        try {
            return (T) genericDAO.buscaPeloID(id);
        } catch (Exception ex) {
        }
        return null;
    }

    @Override
    public List<T> buscaTodos() {
        try {
            return genericDAO.buscaTodos();
        } catch (Exception ex) {
        }
        return null;
    }

    @Override
    public T buscaUmPeloCriterio(Criterion... criterion) {
        try {
            return genericDAO.buscaUmPeloCriterio(criterion);
        } catch (Exception ex) {
        }
        return null;
    }

    @Override
    public T salva(T entity) {
        try {
            genericDAO.salva(entity);
            return entity;
        } catch (Exception ex) {
            System.out.println("Erro " + ex.getMessage());
        }
        return entity;
    }

    @Override
    public T atualiza(T entity) {
        try {
            genericDAO.atualiza(entity);
            return entity;
        } catch (Exception ex) {
            System.out.println("Erro " + ex.getMessage());
        }
        return entity;
    }
}
